package com.schedualnew.mq.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * @author ljy aka ryan
 * @date 2024/3/18$ 11:18$
 * @description TODO
 */
public class HttpUtils {
    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 发送HTTP POST请求，参数为JSON格式。
     * 此方法用于将JSON格式的字符串作为请求体发送到指定的URL，并接收响应。
     *
     * @param url        请求的URL地址。不能为空。
     * @param params     请求的参数，应为符合JSON格式的字符串。
     * @param headParams 请求的头部参数，以键值对形式提供。可以为空，但如果非空，则添加到请求头中。
     * @return 服务器响应的字符串形式内容。如果请求失败，则可能返回null。
     * @throws BusinessException 当发生不支持的编码、客户端协议错误或IO异常时抛出。
     */
    public static String doPostJson(String url, String params, Map<String, String> headParams) {
        String result = null;
        // 创建HTTP客户端实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        try {
            // 创建HTTP POST请求对象
            HttpPost httpPost = new HttpPost(url);

            // 配置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000).build();
            httpPost.setConfig(requestConfig);

            // 将JSON字符串参数转换为StringEntity，并设置请求实体
            httpPost.setEntity(new StringEntity(params, ContentType.create("application/json", "UTF-8")));

            // 如果存在头部参数，则添加到请求头中
            if (headParams != null && !headParams.isEmpty()) {
                for (Map.Entry<String, String> entry : headParams.entrySet()) {
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }

            // 执行请求并获取响应
            response = httpClient.execute(httpPost);

            // 检查响应状态码
            int statusCode = response.getStatusLine().getStatusCode();
            if (HttpStatus.SC_OK != statusCode) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }

            // 从响应中获取内容并转换为字符串
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
            EntityUtils.consume(entity);
        } catch (Exception e) {
            log.error("自动预约->请求异常:" + url + ",params:" + params, e);
        } finally {
            // 无论成功或失败，都关闭资源
            HttpClientUtils.closeQuietly(response);
            HttpClientUtils.closeQuietly(httpClient);
        }
        return result;
    }


}
